package com.googlecode.wannabet.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.googlecode.wannabet.domain.Match;

public class TournamentDetailsService implements IWannabetService {

	public String processRequest(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query = new Query(Match.class.getSimpleName());
		query.addFilter("tournamentID", Query.FilterOperator.EQUAL, new Long(id));
		PreparedQuery preparedQuery = datastore.prepare(query);
		
		StringBuilder builder = new StringBuilder();
		builder.append("<wannabet>");
		builder.append("<tournament>");
		builder.append("<matches>");

		for(Entity result : preparedQuery.asIterable() ) {
			builder.append("<match>");
			
			builder.append("<id>" + result.getProperty("matchID") + "</id>");
			builder.append("<venue>" + result.getProperty("venueID") + "</venue>");
			builder.append("<date>" + result.getProperty("eventDate") + "</date>");
			builder.append("<time></time>");
			builder.append("<day></day>");
			
			builder.append("<teams>");
			
			builder.append("<team>");
			builder.append("<id>" + result.getProperty("team1") + "</id>");
			builder.append("<name></name>");
			builder.append("</team>");
			
			builder.append("<team>");
			builder.append("<id>" + result.getProperty("team2") + "</id>");
			builder.append("<name></name>");
			builder.append("</team>");
			
			builder.append("</teams>");

			builder.append("</match>");
		}

		builder.append("</matches>");
		builder.append("</tournament>");
		builder.append("</wannabet>");
		
		return builder.toString();
	}

}
